#include <SDL.h>
#include <stdlib.h>

// 屏幕宽高
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

// 火焰像素数组大小
#define FIRE_WIDTH 640
#define FIRE_HEIGHT 400

// 火焰颜色梯度
static const SDL_Color firePalette[] = {
		{7,   7,   7},
		{31,  7,   7},
		{47,  15,  7},
		{71,  15,  7},
		{87,  23,  7},
		{103, 31,  7},
		{119, 31,  7},
		{143, 39,  7},
		{159, 47,  7},
		{175, 63,  7},
		{191, 71,  7},
		{199, 71,  7},
		{223, 79,  7},
		{223, 87,  7},
		{223, 87,  7},
		{215, 95,  7},
		{215, 95,  7},
		{215, 103, 15},
		{207, 111, 15},
		{207, 119, 15},
		{207, 127, 15},
		{207, 135, 23},
		{199, 135, 23},
		{199, 143, 23},
		{199, 151, 31},
		{191, 159, 31},
		{191, 159, 31},
		{191, 167, 39},
		{191, 167, 39},
		{191, 175, 47},
		{183, 175, 47},
		{183, 183, 47},
		{183, 183, 55},
		{207, 207, 111},
		{223, 223, 159},
		{239, 239, 199},
		{255, 255, 255}
};

// 火焰像素数组
int firePixels[FIRE_WIDTH * FIRE_HEIGHT] = { 0 };

// 初始化火焰数组
void initFire() {
	for (int x = 0; x < FIRE_WIDTH; x++) {
		firePixels[(FIRE_HEIGHT - 1) * FIRE_WIDTH + x] = 36;
	}
}

// 更新火焰效果
void updateFire() {
	for (int x = 0; x < FIRE_WIDTH; x++) {
		for (int y = 0; y < FIRE_HEIGHT; y++) {
			int srcPixelIndex = y * FIRE_WIDTH + x;
			int dstPixelIndex = srcPixelIndex - FIRE_WIDTH + (rand() % 3 - 1);
			if (dstPixelIndex >= 0) {
				int decay = rand() % 3;
				firePixels[dstPixelIndex] = firePixels[srcPixelIndex] - (decay & 1);
			}
		}
	}
}

// 绘制火焰效果
void drawFire(SDL_Renderer* renderer) {
	for (int x = 0; x < FIRE_WIDTH; x++) {
		for (int y = 0; y < FIRE_HEIGHT; y++) {
			int index = firePixels[y * FIRE_WIDTH + x];
			SDL_SetRenderDrawColor(renderer, firePalette[index].r, firePalette[index].g, firePalette[index].b, 255);
			SDL_RenderDrawPoint(renderer, x, y);
		}
	}
}

int main(int argc, char* args[]) {
	// 初始化SDL
	SDL_Init(SDL_INIT_VIDEO);

	// 创建窗口和渲染器
	SDL_Window* window = SDL_CreateWindow("Pixel Fire Effect", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

	// 初始化火焰效果
	initFire();

	// 主循环
	bool quit = false;
	SDL_Event e;
	while (!quit) {
		while (SDL_PollEvent(&e) != 0) {
			if (e.type == SDL_QUIT) {
				quit = true;
			}
		}

		// 更新和绘制火焰效果
		updateFire();
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
		SDL_RenderClear(renderer);
		drawFire(renderer);
		SDL_RenderPresent(renderer);

		// 控制帧率
		SDL_Delay(30);
	}

	// 清理SDL
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

	return 0;
}
